package io.xiaojl.xj2ee.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import io.xiaojl.xj2ee.common.annotion.DataFilter;
import io.xiaojl.xj2ee.modules.sys.entity.SysDeptEntity;
import io.xiaojl.xj2ee.modules.sys.repository.SysDeptRepository;
import io.xiaojl.xj2ee.modules.sys.service.SysDeptService;


@Service("sysDeptService")
public class SysDeptServiceImpl implements SysDeptService {
	@Autowired
	private SysDeptRepository sysDeptRepository;
	
	@Override
	@DataFilter(subDept = true, user = false)
	public List<SysDeptEntity> queryList(Map<String, Object> params){
		List<SysDeptEntity> deptList = sysDeptRepository.findByDelFlag(0);
		
		for(SysDeptEntity sysDeptEntity : deptList){
			SysDeptEntity parentDeptEntity =  sysDeptRepository.getOne(sysDeptEntity.getParentId());
			if(parentDeptEntity != null){
				sysDeptEntity.setParentName(parentDeptEntity.getName());
			}
		}
		return deptList;
	}

	@Override
	public List<Long> queryDetpIdList(Long parentId) {
		return sysDeptRepository.queryDetpIdList(parentId);
	}

	@Override
	public List<Long> getSubDeptIdList(Long deptId){
		//部门及子部门ID列表
		List<Long> deptIdList = new ArrayList<>();

		//获取子部门ID
		List<Long> subIdList = queryDetpIdList(deptId);
		getDeptTreeList(subIdList, deptIdList);

		return deptIdList;
	}

	/**
	 * 递归
	 */
	private void getDeptTreeList(List<Long> subIdList, List<Long> deptIdList){
		for(Long deptId : subIdList){
			List<Long> list = queryDetpIdList(deptId);
			if(list.size() > 0){
				getDeptTreeList(list, deptIdList);
			}

			deptIdList.add(deptId);
		}
	}

	@Override
	public SysDeptEntity selectById(Long deptId) {
		return sysDeptRepository.getOne(deptId);
	}

	@Override
	public int insert(SysDeptEntity dept) {
		sysDeptRepository.save(dept);
		return 1;
	}

	@Override
	public int updateById(SysDeptEntity dept) {
		sysDeptRepository.save(dept);
		return 1;
	}

	@Override
	public int deleteById(long deptId) {
		sysDeptRepository.deleteById(deptId);
		return 1;
	}

}
